package com.han.yweb;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpBaseSocket {

    private static final ExecutorService executor =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true) {
            Socket socket = serverSocket.accept();
            executor.execute(() -> task(socket));
        }
    }

    public static void task(Socket socket) {

        try (OutputStream output = socket.getOutputStream();
             InputStream input = socket.getInputStream()) {

            parseRequest(input);
            sendResponse(output);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException ignore) {
            }
        }

    }

    private static void parseRequest(InputStream input) throws IOException {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = readInputStream(input);
        System.out.println(new String(bytes));
//        byte[] buffer = new byte[128];
//        int len;
//        while ((len =input.read(buffer)) != -1) {
//            for (int i = 0; i < len; i++) {
//                sb.append((char) buffer[i]);
//            }
//        }

        System.out.println(sb);
    }
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static void sendResponse(OutputStream output) throws IOException {
//        byte[] bytes = new byte[1024];
//        File file = new File("test.txt");
//        if (file.exists()) {
//            FileInputStream fis = new FileInputStream(file);
//            int ch = fis.read(bytes, 0, 1024);
//            while (ch != -1) {
//                output.write(bytes, 0, ch);
//                ch = fis.read(bytes, 0, 1024);
//            }
//        }

        String message = "HTTP/1.1 200 OK\r\n" +
                "Content-Type: text/html\r\n" +
                "Content-Length: 11\r\n" +
                "\r\n" +
                "<h1>Hello didi</h1>";
        output.write(message.getBytes());
    }
}
